#include <raylib.h>
#include <stdbool.h>
#include <complex.h>
#define _OUTPUT_FILE "outpng/Mandelbrot.png"
#ifndef __IMAGE_OUT_OFF__
#define STB_IMAGE_IMPLEMENTATION
#include "include/stb_image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "include/stb_image_write.h"
#endif

#ifndef __IMAGE_OUT_OFF__
    typedef struct {
        int w,h,ch;
        unsigned char *data;
    }__out_image;
#endif

complex double c = 0;
bool ok = true;
complex double fc[30] = {0};
int mx[4000][4000] = {0};

//复平面坐标转换屏幕坐标
Vector2 real_to_mpos(complex double val){
    double x = creal(val);
    double y = cimag(val);
    int px = (x-(-2.0))/0.001;
    int py = (y-(-2.0))/0.001;
    return (Vector2){px,4000-py};
}

int main(){
    //计算某点是否满足该集合
    for (double i = -2.0;i < 2.0;i+=0.001){
        for (double ii=-2.0;ii < 2.0;ii+=0.001){
            fc[0] = 0;
            ok = true;
            c = i + ii*I;
            for ( int j = 0;j<29 ;j++){
                fc[j+1] = fc[j]*fc[j] + c;
                if (cabs(fc[j+1])>2.0){
                    ok = false;
                    break;
                }
            }
            if (ok==true){
                Vector2 npos = real_to_mpos(c);
                mx[(int)npos.x][(int)npos.y] = 1;
            }
        }
    }
#ifndef __IMAGE_OUT_OFF__
    bool writed = false;
    __out_image imgo = (__out_image){.w = 2900,.h=2120,.ch=1,.data = (unsigned char*)calloc(2900*2120*1,1)};
#endif
    //绘制
    InitWindow(2900, 2120, "hello");
    SetTargetFPS(30);
    while (!WindowShouldClose()) {
        BeginDrawing();
        ClearBackground(WHITE);
        for (int i =100;i<3000 ;i++ ) {
            for (int j=940;j<3060 ; j++){
                if (mx[i][j]!=0){
#ifndef __IMAGE_OUT_OFF__
                    // if(writed == false){
                    imgo.data[(j-940)*imgo.w+(i-100)]=255;
//                         writed = true;
//                     }
#endif
                    DrawPixel(i-100,j-940 , BLACK);
                }
            }
        }
        EndDrawing();
    }
#ifndef __IMAGE_OUT_OFF__
    stbi_write_png(_OUTPUT_FILE, imgo.w, imgo.h, imgo.ch, imgo.data, imgo.w *imgo.ch);
    free(imgo.data);
#endif
    CloseWindow();
}
